﻿"use strict";
define(["service/service", "ng-file-upload"], function (service) {
    service.factory("httpService", function ($http, $q, $uibModal, Upload) {
        var methods = {
            call: function (type, url, params, data) {
                return $http({ method: type, url: url, params: params, data: data }).success(methods.success).error(methods.errorModal);
            },
            success: function (data) {
                return data;
            },
            errorModal: function (data, status) {
                $uibModal.open({
                    templateUrl: '/tpl/errorModal.html ',
                    backdrop: "static",
                    controller: "errorModal",
                    resolve: {
                        error: function () {
                            if (status == 401)
                                data.status = status;
                            if (status == 404)
                                return { "result_msg": "请求不存在" };
                            else
                                return data;
                        }
                    }
                });
            },
            query: function (url, params) {
                var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行  
                $http({ method: 'get', url: url, params: params }).success(function (data, status, headers, config) {
                    deferred.resolve(data);  // 声明执行成功，即http请求数据成功，可以返回数据了  
                }).error(function (data, status, headers, config) {
                    deferred.reject(data);   // 声明执行失败，即服务器返回错误  
                });
                return deferred.promise;   // 返回承诺，这里并不是最终数据，而是访问最终数据的API  
            },
            get: function (url, params) {
                return methods.call('GET', url, params);
            },
            put: function (url, data) {
                return methods.call('PUT', url, null, data);
            },
            post: function (url, data) {
                return methods.call('POST', url, null, data);
            },
            'delete': function (url, data) {
                return methods.call('DELETE', url, data, null);
            },
            upload: function (url, data) {
                return Upload.upload({
                    url: url,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' },
                    data: data
                }).success(function (data) {
                    return data;
                }).error(methods.errorModal)
            }
        }
        return methods;
    })
});